package ylog

import (
	"context"
	"fmt"
	"github.com/google/uuid"
	"github.com/rs/zerolog"
	"gopkg.in/natefinch/lumberjack.v2"
	"os"
)

func getLevel(level int) (l zerolog.Level) {
	if level < -1 || level > 7 {
		level = 0
	}

	switch level {
	case -1:
		l = zerolog.TraceLevel
	case 0:
		l = zerolog.DebugLevel
	case 1:
		l = zerolog.InfoLevel
	case 2:
		l = zerolog.WarnLevel
	case 3:
		l = zerolog.ErrorLevel
	case 4:
		l = zerolog.FatalLevel
	case 5:
		l = zerolog.PanicLevel
	case 6:
		l = zerolog.NoLevel
	case 7:
		l = zerolog.Disabled
	}
	return l
}

func Ctx(ctx context.Context) *zerolog.Logger {
	return zerolog.Ctx(ctx)
}

func WithContext(ctx context.Context, log *zerolog.Logger) context.Context {
	ctx = log.With().Str("traceId", uuid.New().String()).Logger().WithContext(ctx)
	return ctx
}

func NewLog(conf LogConf) *zerolog.Logger {
	basicLog := zerolog.ConsoleWriter{Out: os.Stdout, TimeFormat: "2006-01-02 15:04:05", NoColor: false}

	if !conf.Debug {
		basicLog.NoColor = true

		basicLog.Out = &lumberjack.Logger{
			Filename:   fmt.Sprintf("%s%s", conf.Path, conf.Name),
			MaxSize:    conf.MaxSize,
			MaxAge:     conf.MaxAge,
			MaxBackups: conf.MaxBackups,
			LocalTime:  conf.LocalTime,
			Compress:   false,
		}
	}
	log := zerolog.New(basicLog).With().Timestamp().Caller().Logger().Level(getLevel(conf.Level))

	return &log
}
